/**
 * 
 */
package com.estock.platform.http;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.estock.common.model.security.Index;
import com.estock.common.model.security.RealTimeIndex;
import com.estock.common.model.security.enums.StockType;
import com.estock.platform.http.client.GetClientProxy;
import com.estock.platform.http.client.URLConnectionClient;
import com.estock.platform.http.consts.RequestConsts;
import com.estock.platform.http.request.StockClientRequest;
import com.estock.platform.http.response.BaseResponse;
import com.estock.platform.http.response.SinaIndexBulkResponse;
import com.estock.platform.http.response.SinaRealTimeIndexBulkResponse;
import com.estock.platform.http.utils.RequestUtil;

/**
 * @author richard
 *
 */
public class SinaIndexBulkConn extends AbstractConnection {
	
	private static Logger logger = Logger.getLogger(SinaIndexBulkConn.class);
	
	public BaseResponse request(List<Index> dummyIndexes, boolean isRealTimeTask) throws Exception {
		try {
			if (isRealTimeTask) {
				SinaRealTimeIndexBulkResponse response = 
						getResponse(SinaRealTimeIndexBulkResponse.class, dummyIndexes);
				// for testing
		    	List<RealTimeIndex> indexes = response.getRealTimeindexes();
		    	if (indexes != null) {
		    		logger.info("get sinajs realtime indexes with size: " + indexes.size());
		    	}
		    	return response;
			}
			
			SinaIndexBulkResponse response = 
					getResponse(SinaIndexBulkResponse.class, dummyIndexes);
			// for testing
	    	List<Index> indexes = response.getIndexes();
	    	if (indexes != null) {
	    		logger.info("get sinajs bulk indexes with size: " + indexes.size());
	    	}
	    	return response;
		} catch (Exception e) {
			throw new RuntimeException("can not get valid indexes information.", e);
		}
        
	}
	
	@Override
	protected GetClientProxy createStockClientProxy() {
		return new GetClientProxy(new URLConnectionClient() {
			@Override
			protected String saveStreamAsString(InputStream inputStream) 
					throws IOException {
				return RequestUtil.saveStreamAsGBK(inputStream);
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	protected StockClientRequest buildStockClientRequest(Object... params) throws Exception {
		return (StockClientRequest) StockClientRequest
				.getSinaJSRequestBuilder(RequestConsts.URI_SINA_INDEX_JS)
				.appendBulkIndexes((List<Index>) params[0])
                .buildQueryMessage();
	}
	
	
	/**
	 * Test Method
	 * 
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		List<Index> indexes = new ArrayList<Index>();
		indexes.add(new Index("000010", StockType.SH.getType()));
		indexes.add(new Index("399001", StockType.SZ.getType()));
		new SinaIndexBulkConn().request(indexes, false);
	}

}
